import datasource from '../src/framework/datasource'
import { Word, Phrases, Translations, WordType } from '../src/word/dao/WorkDao'
import { WordEntity } from 'spen-common/src/entity/WordEntity'

async function wordType(id: number, name: string) {
  await WordType.create({
    id: id,
    name: name
  })
}

let array = ['1-初中-顺序', '2-高中-顺序', '3-CET4-顺序', '4-CET6-顺序' , '5-考研-顺序', '6-托福-顺序', '7-SAT-顺序'];

async function initType() {
  for (let i in array) {
    let a: string[] = array[i].split('-');
    await wordType(parseInt(a[0]), a[1] + '-' + a[2]);
  }
};

/** 数组分片 */
function chunkArray(array: any[], chunkSize: number) {
  let result: any[] = [];
  for (let i = 0; i < array.length; i += chunkSize) {
    result.push(array.slice(i, i + chunkSize));
  }
  return result;
}

async function wordInsert(value: WordEntity[], typeId: number, start: number) {
  try {
  let words : any[] = [];
  value.forEach((d, index)=>{
    words.push({
        id: index+start,
        word: d.word == null ? '' : d.word,
        typeId: typeId
      });
    });

    let wordEntity: any[] = chunkArray(words, 3000);
    for(let i = 0;i<wordEntity.length;i++){
      let data = wordEntity[i];
      await Word.bulkCreate(data, {fields: [
        'id', 'word', 'typeId'
      ]});
    }

    let translationList: any[] = [];
    let phrasesList: any[] = [];
    for (let i in value) {
      const wordId = start + parseInt(i);
      let entity = value[i];
      let translations = entity.translations;
      let phrases = entity.phrases;
      if (translations != null) {
    
        translations.forEach((d) => {
          d.translation = d.translation == null ? '' : d.translation;
          d.type = d.type == null ? '' : d.type;
          d['wordId'] = wordId;
          translationList.push(d);
        })
      }
      if (phrases != null) {
        phrases.forEach((d) => {
          d.phrase = d.phrase == null ? '' : d.phrase;
          d.translation = d.translation == null ? '' : d.translation;
          d['wordId'] = wordId;
          phrasesList.push(d);
        })
        
      }
    }
    let tdata = chunkArray(translationList, 3000);
    for(let i =0;i<tdata.length;i++){
      await Translations.bulkCreate(tdata[i], { fields: ['translation', 'type', 'wordId'] });
    }
    
    let pdata = chunkArray(phrasesList, 3000);
    for(let i = 0;i< pdata.length; i++){
      await Phrases.bulkCreate(pdata[i], {fields: ['phrase', 'translation', 'wordId']});
    }
  } catch (err) {
    console.log(err)
  }
}

async function setWord() {
  let index = 1;
  for (let i in array) {
    let a: string[] = array[i].split('-');
    let data: any = await import('./' + array[i] + '.json');
    await wordInsert(data.default, parseInt(a[0]), index);
    index=index+data.default.length+1;
  }
};

(async () => {
  await datasource.authenticate();
  await datasource.sync();
  await initType();
  await setWord();
  console.log("完成");
  datasource.close();
})();



